package com.tbit.uqbike.webmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.business.UserInfo;
import com.tbit.uqbike.object.pojo.Eventdetail;
import com.tbit.uqbike.object.pojo.InviteLog;
import com.tbit.uqbike.object.pojo.InviteNewEvent;
import com.tbit.uqbike.object.pojo.InviteTotal;
import com.tbit.uqbike.object.pojo.dto.InviteDetailQueryDTO;
import com.tbit.uqbike.object.pojo.dto.InviteTotalQueryDTO;
import com.tbit.uqbike.object.pojo.vo.InviteLogVO;
import com.tbit.uqbike.object.pojo.vo.InviteTotalVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.value.Page;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.InviteNewEventService;
import com.tbit.uqbike.webmanager.dao.core.ActivityDao;
import com.tbit.uqbike.webmanager.dao.log.InviteLogDao;
import com.tbit.uqbike.webmanager.dao.log.InviteTotalDao;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.BeanUtils;
import com.tbit.uqbike.webmanager.util.PageHelperUtil;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import com.tbit.uqbike.webmanager.util.weixin.TenpayUtil;
import com.tbit.utils.DateTimeUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 活动表(InviteNewEvent)表控制层
 *
 * @author jing
 * @since 2020-12-30 17:31:17
 */
@RestController
@RequestMapping("/invitenewevent")
public class InviteNewEventController extends BaseController{
    /**
     * 服务对象
     */
    @Resource
    private InviteNewEventService inviteNewEventService;
    @Resource
    private InviteTotalDao inviteTotalDao;
    @Resource
    private InviteLogDao inviteLogDao;
    @Resource
    private ActivityDao activityDao;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PostMapping("/selectList")
    public JsonResult selectList(Integer id) {
        return JsonResult.ok(this.inviteNewEventService.queryById(id));
    }

    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:分页条件查询
     * @createDate 2020/12/30 18:38
     */
    @PostMapping("/selectByInvitenewevent")
    public JsonResult selectByInviteNewEvent(InviteNewEvent inviteNewEvent) {
        Assert.notNull(inviteNewEvent.getAccountId(), "ver.areaId.notNull");
        inviteNewEvent.setPage(new Page(inviteNewEvent.getPageNO(), inviteNewEvent.getRowCount()));
        PageHelperUtil.initPage(inviteNewEvent.getPage());
        PageInfo<InviteNewEvent> results = new PageInfo<>(inviteNewEventService.queryByInviteNewEvent(inviteNewEvent));
        return JsonResult.ok(results.getList(), (int) results.getTotal());
    }

    /**
     * @param id
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:删除即将该活动置为失效
     * @createDate 2020/12/30 18:38
     */
    @PostMapping("/deleteById")
    public JsonResult deleteById(Integer id) {
        inviteNewEventService.update(new InviteNewEvent(id, 0));
        return JsonResult.ok();
    }

    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:插入活动详情
     * @createDate 2020/12/31 14:14
     */
    @PostMapping("/insert")
    public JsonResult insert(InviteNewEvent inviteNewEvent) {
        inviteNewEvent.setVaildDay(DateTimeUtil.getDayCountByRange(DateTimeUtil.formatDateYMD(inviteNewEvent.getStartTime()), DateTimeUtil.formatDateYMD(inviteNewEvent.getEndTime())));
        inviteNewEvent.setIsvalid(1);
        if (inviteNewEvent.getDetailId() == null) {
            inviteNewEvent.setDetailId(0);
        }
        inviteNewEventService.insert(inviteNewEvent);
        return JsonResult.ok();
    }

    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:更新活动详情
     * @createDate 2020/12/31 14:14
     */
    @PostMapping("/update")
    public JsonResult update(InviteNewEvent inviteNewEvent) {
        inviteNewEvent.setVaildDay(DateTimeUtil.getDayCountByRange(DateTimeUtil.formatDateYMD(inviteNewEvent.getStartTime()), DateTimeUtil.formatDateYMD(inviteNewEvent.getEndTime())));
        inviteNewEventService.update(inviteNewEvent);
        return JsonResult.ok();
    }


    @PostMapping("/selectActivity")
    public JsonResult selectActivity(InviteNewEvent inviteNewEvent) {
        Eventdetail eventdetail = inviteNewEventService.selectActivity(inviteNewEvent);
        List<Eventdetail> list = new ArrayList<>();
        list.add(eventdetail);
        return JsonResult.ok(list);
    }


    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description: 绑定活动配置
     * @createDate 2020/12/31 14:15
     */
    @PostMapping("/bindingActivity")
    public JsonResult bindingActivity(InviteNewEvent inviteNewEvent) {
        InviteNewEvent invitenew = inviteNewEventService.queryById(inviteNewEvent.getId());
        if (null != invitenew && invitenew.getDetailId() != 0) {
            throw new BaseException(SystemCodeEnum.FREE_CONFIGURATION_HAS_BEEN_BOUND);
        }
        inviteNewEventService.bindingActivity(inviteNewEvent);
        return JsonResult.ok();
    }

    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:删除活动配置
     * @createDate 2020/12/31 14:15
     */
    @PostMapping("/untieActivity")
    public JsonResult untieActivity(InviteNewEvent inviteNewEvent) {
        inviteNewEventService.untieActivity(inviteNewEvent);
        return JsonResult.ok();
    }

    /**
     * @param inviteNewEvent
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description: 修改活动配置
     * @createDate 2020/12/31 14:16
     */
    @PostMapping("/updateActivity")
    public JsonResult updateActivity(InviteNewEvent inviteNewEvent) {
        inviteNewEventService.updateActivity(inviteNewEvent);
        return JsonResult.ok();
    }

    /**
     * 查询邀新活动明细
     * @param queryDTO 查询参数
     * @return
     */
    @GetMapping("/detail")
    public Result<PageResult<InviteLogVO>> inviteLogDetail(InviteDetailQueryDTO queryDTO){
        IPage<InviteLog> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(queryDTO.getPageNO(), queryDTO.getPageSize());
        IPage<InviteLog> inviteLogIPage = inviteLogDao.selectPage(page, getInviteLogLambdaQueryWrapper(queryDTO));
        List<InviteLogVO> res = inviteLogIPage.getRecords().stream().map(x -> {
            InviteLogVO inviteLogVO = BeanUtils.copyProperties(x, InviteLogVO.class);
            inviteLogVO.format();
            return inviteLogVO;
        }).collect(Collectors.toList());
        PageResult<InviteLogVO> inviteLogVOPageResult = new PageResult<>((int) inviteLogIPage.getCurrent(), (int) inviteLogIPage.getSize(), inviteLogIPage.getTotal(), (int) inviteLogIPage.getPages(), res);
        return Result.success(inviteLogVOPageResult);
    }

    private LambdaQueryWrapper<InviteLog> getInviteLogLambdaQueryWrapper(InviteDetailQueryDTO queryDTO){
        return new LambdaQueryWrapper<InviteLog>().eq(InviteLog::getAccountId,queryDTO.getAccountId())
                .eq(Objects.nonNull(queryDTO.getEventId()),InviteLog::getEventId,queryDTO.getEventId())
                .eq(Objects.nonNull(queryDTO.getInviterPhone()),InviteLog::getInviterPhone,queryDTO.getInviterPhone())
                .eq(Objects.nonNull(queryDTO.getInviteesPhone()),InviteLog::getInviteesPhone,queryDTO.getInviteesPhone())
                .eq(Objects.nonNull(queryDTO.getRideOrderNO()),InviteLog::getRideOrderNO,queryDTO.getRideOrderNO())
                .between(Objects.nonNull(queryDTO.getStartTime()) && Objects.nonNull(queryDTO.getEndTime())
                        ,InviteLog::getRegisterTime,queryDTO.getStartTime(),queryDTO.getEndTime());
    }

    /**
     * 邀新活动明细导出
     * @param queryDTO 查询参数
     * @return
     */
    @GetMapping("/detail-export")
    public Result<String> inviteLogDetailExport(InviteDetailQueryDTO queryDTO){
        List<InviteLog> inviteLogList = inviteLogDao.selectList(getInviteLogLambdaQueryWrapper(queryDTO));
        List<InviteLogVO> inviteLogVOList = inviteLogList.stream().map(x -> {
            InviteLogVO inviteLogVO = BeanUtils.copyProperties(x, InviteLogVO.class);
            inviteLogVO.format();
            return inviteLogVO;
        }).collect(Collectors.toList());
        ExcelUtil<InviteLogVO> excelUtil = new ExcelUtil<>(InviteLogVO.class);
        JsonResult jsonResult = excelUtil.exportExcel(inviteLogVOList, "邀新活动明细列表");
        return Result.success(jsonResult.getData().toString());
    }

    private LambdaQueryWrapper<InviteTotal> getInviteTotalLambdaQueryWrapper(InviteTotalQueryDTO queryDTO){
        return new LambdaQueryWrapper<InviteTotal>().eq(InviteTotal::getAccountId,queryDTO.getAccountId())
                .eq(Objects.nonNull(queryDTO.getEventId()),InviteTotal::getEventId,queryDTO.getEventId())
                .eq(Objects.nonNull(queryDTO.getInviterPhone()),InviteTotal::getInviterPhone,queryDTO.getInviterPhone());
    }

    /**
     * 查询邀新活动汇总
     * @param queryDTO 查询参数
     * @return
     */
    @GetMapping("/total")
    public Result<PageResult<InviteTotalVO>> inviteLogTotal(InviteTotalQueryDTO queryDTO){
        IPage<InviteTotal> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(queryDTO.getPageNO(), queryDTO.getPageSize());
        IPage<InviteTotal> inviteTotalIPage = inviteTotalDao.selectPage(page, getInviteTotalLambdaQueryWrapper(queryDTO));
        List<InviteTotalVO> res = inviteTotalIPage.getRecords().stream().map(x -> {
            InviteTotalVO inviteTotalVO = BeanUtils.copyProperties(x, InviteTotalVO.class);
            return inviteTotalVO;
        }).collect(Collectors.toList());
        PageResult<InviteTotalVO> inviteLogVOPageResult = new PageResult<>((int) inviteTotalIPage.getCurrent(), (int) inviteTotalIPage.getSize(), inviteTotalIPage.getTotal(), (int) inviteTotalIPage.getPages(), res);
        return Result.success(inviteLogVOPageResult);
    }

    /**
     * 查询邀新活动汇总导出
     * @param queryDTO 查询参数
     * @return
     */
    @GetMapping("/total-export")
    public Result<String> inviteLogTotalExport(InviteTotalQueryDTO queryDTO){
        List<InviteTotal> inviteTotalList = inviteTotalDao.selectList(getInviteTotalLambdaQueryWrapper(queryDTO));
        List<InviteTotalVO> inviteTotalVOList = inviteTotalList.stream().map(x -> BeanUtils.copyProperties(x, InviteTotalVO.class)).collect(Collectors.toList());
        ExcelUtil<InviteTotalVO> excelUtil = new ExcelUtil<>(InviteTotalVO.class);
        JsonResult jsonResult = excelUtil.exportExcel(inviteTotalVOList, "邀新活动汇总列表");
        return Result.success(jsonResult.getData().toString());
    }

    /**
     * 暂停活动
     * @return
     */
    @PutMapping("/pause/{eventId}")
    public Result<Boolean> pause(@PathVariable("eventId") Integer eventId){
        // 进行中 & 关闭
        activityDao.updateState(eventId,1,0);
        return Result.success(true);
    }

    /**
     * 获取活动二维码前端所需的Code
     * @param eventId 活动id
     * @return
     */
    @GetMapping("/getCode/{eventId}")
    public Result<String> getCode(@PathVariable("eventId") Integer eventId){
        UserInfo userInfo = fetchUserInfo();
        String code = userInfo.getAccountUserId() + "" + TenpayUtil.buildRandom(6);
        return Result.success(code);
    }

}